import React, {useState, useEffect} from 'react';
import { Modal, Form, Input } from 'antd';
import { FormInstance } from 'antd/lib/form';
import OrgTypeListComponent from './OrgTypeListComponent';
import ParentOrgListComponent from './ParentOrgListComponent';
import { OrgItem } from '../data';

interface CreateFormProps {
  modalVisible: boolean;
  onSubmit: (values: OrgItem) => void;
  onCancel: () => void;
  values:OrgItem;
}

const layout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 16 },
};

const formRef = React.createRef<FormInstance>();

const AddOrgModel: React.FC<CreateFormProps> = (props) => {
  const { modalVisible, onSubmit, onCancel, values } = props;
  const [disabled, handleDisabled] = useState<boolean>(true);//机构类型是否可用，根据上级机构
  const [parentOrgId, setParentOrgId] = useState<number>(10000);//【机构类型】与【上级机构】联动
  const [form] = Form.useForm();

  useEffect(() => {
    if(modalVisible){
      if(values){//编辑
        form.setFieldsValue({
          id: values.id,
          orgName: values.orgName,
          parentOrgId: values.parentOrgId,
          orgTypeId: values.orgTypeId,
        });
        setParentOrgId(values.parentOrgId)
        handleDisabled(false);
      }else{//新建
        form.resetFields();
        handleDisabled(true);
      }
    }
  },[modalVisible]);

  const handleFinish = (values: { [key: string]: any }) => {
    if (onSubmit) {
      onSubmit(values as OrgItem);
    }
  };

  const handleUpdate = () => {
    if (!form) return;
    form.submit();
  };

  const modalFooter = { okText: '保存', onOk: handleUpdate, onCancel };

  const renderContent = () => {
    return (
      <>
        <Form.Item name="id" style={{ display: 'none' }}></Form.Item>
        <Form.Item
          name="orgName"
          label="机构名称"
          rules={[{ required: true, max: 64, whitespace: true }]}
        >
          <Input placeholder="请输入机构名称" style={{ width: 200 }}/>
        </Form.Item>
        <Form.Item
          name="parentOrgId"
          label="上级机构"
          rules={[{ required: true }]}
        >
          <ParentOrgListComponent 
            defaultvalue={values?values.parentOrgId:-1}
            type="topOrgId"
            disabled={values?true:false}
            selectChange={(value,topOrgId) => {
              form.setFieldsValue({"parentOrgId":value,"orgTypeId":undefined});
              setParentOrgId(topOrgId);
              if(value){
                handleDisabled(false);
              }else{
                handleDisabled(true);
              }
            }}
          ></ParentOrgListComponent>
        </Form.Item>
         <Form.Item
            noStyle
            shouldUpdate={(prevValues, currentValues) =>
            prevValues.type !== currentValues.type
            }   
        >
        {({ getFieldValue }) => {
            return getFieldValue("parentOrgId") != 10000? (
              <Form.Item
                name="orgTypeId"
                label="机构类型"
                rules={[{ required: true }]}
              >
                <OrgTypeListComponent
                  disabled={disabled}
                  defaultvalue={values?values.orgTypeId:-1} 
                  selector={parentOrgId}
                  selectChange={(value) => form.setFieldsValue({"orgTypeId":value})}
                >
                </OrgTypeListComponent>
              </Form.Item>
            ):null
          }}
          </Form.Item>
      </>
    );
  };

  return (
    <Modal
      destroyOnClose
      width={400}
      title={values ? "编辑机构":"添加机构"}
      visible={modalVisible}
      {...modalFooter}
    >
      <Form {...layout} ref={formRef} form={form} onFinish={handleFinish}>
        {renderContent()}
      </Form>
    </Modal>
  );
};

export default AddOrgModel;
